#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from datetime import timedelta
import traceback
from flask_jwt_extended import JWTManager

from . import api_action, api_auth, api_fm

from flask import Flask, url_for, jsonify
from flask import request

from lj_tool.tool_json import lj_json_loads

app = Flask(__name__)
app.config["SECRET_KEY"] = "lj-20230629"
app.config["JWT_SECRET_KEY"] = "lj-20230629"
# token 有效期 10年
app.config['JWT_ACCESS_TOKEN_EXPIRES'] = timedelta(days=3650)
jwt = JWTManager(app)

app.register_blueprint(api_action.api_action, url_prefix='/action')
app.register_blueprint(api_auth.api_auth, url_prefix='/auth')
app.register_blueprint(api_fm.api_fm, url_prefix='/fm')


@app.after_request
def after_request(response):
    if response.status_code == 404:
        return response

    data = lj_json_loads(str(response.get_data(as_text=True)))
    if response.status_code == 200:
        pass
    elif isinstance(data, dict):
        data = data.get('error')
    return jsonify({
        'data': data,
        'code': response.status_code
    })

# 全局异常处理装饰器


@app.errorhandler(Exception)
def handle_exception(e):
    # 打印异常信息
    traceback.print_exc()

    # 返回自定义的错误响应
    response = {
        "data": str(e),
        "code": 500
    }
    return jsonify(response)


@app.route('/', methods=['GET'])
def home():
    return '<h1>欢迎访问系统...</h1>'


@app.route('/redirect', methods=['GET'])
def redirect():
    return redirect(url_for('/test/sss'))


@app.route('/upload', methods=['POST'])
def upload_file():
    f = request.files['the_file']
    f.save('/var/www/uploads/uploaded_file.txt')


def init():
    app.run(host='0.0.0.0', port=38888, debug=True)


if __name__ == '__main__':
    init()
